package com.example.database.dao.impl;

import com.example.database.dao.DeptInstructorDao;
import com.example.database.entity.DeptInstructor;
import com.example.database.util.MySqlConnector;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Repository
public class DeptInstructorDaoImpl implements DeptInstructorDao
{
    @Override
    public DeptInstructor findDeptInstructorById(Integer teacher_id)
    {
        if (teacher_id == null) return null;
        DeptInstructor deptInstructor = new DeptInstructor();
        try {
            Connection conn = new MySqlConnector().getConnection();
            String sql = "select * from dept_instructor where teacher_id = ?;";
            try (PreparedStatement statement = conn.prepareStatement(sql))
            {
                statement.setInt(1, teacher_id);
                ResultSet resultSet = statement.executeQuery();
                if (resultSet.next())
                {
                    deptInstructor.setTeacher_id(resultSet.getInt("teacher_id"));
                    deptInstructor.setPassword(resultSet.getString("password"));
                    deptInstructor.setName(resultSet.getString("teacher_name"));
                    deptInstructor.setEmail(resultSet.getString("email"));
                    deptInstructor.setPhone(resultSet.getString("phone"));
                    deptInstructor.setAddress(resultSet.getString("address"));
                    deptInstructor.setDepartment_id(resultSet.getInt("department_id"));
                }
                conn.close();
                return deptInstructor;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Boolean addDeptInstructor(DeptInstructor deptInstructor) {
        if (deptInstructor == null) return Boolean.FALSE;
        try {
            Connection conn = new MySqlConnector().getConnection();
            String sql = "insert into dept_instructor (teacher_id,password,teacher_name, phone, email," +
                    " address) VALUES (?,?,?,?,?,?);";
            try (PreparedStatement statement = conn.prepareStatement(sql)){
                statement.setInt(1,deptInstructor.getTeacher_id());
                statement.setString(2,deptInstructor.getPassword());
                statement.setString(3,deptInstructor.getName());
                statement.setString(4,deptInstructor.getPhone());
                statement.setString(5,deptInstructor.getEmail());
                statement.setString(6,deptInstructor.getAddress());
                if (statement.executeUpdate() <= 0)return Boolean.FALSE;
                conn.close();
                return Boolean.TRUE;
            }
        }catch (Exception e){
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }
}
